//
//  MOPublishedViewController.m
//  星星计划
//
//  Created by 莫业金 on 16/7/5.
//  Copyright © 2016年 moyejin. All rights reserved.
//
#import "MOTextView.h"
#import "MOPublishedViewController.h"
#import "JFImagePickerController.h"
#import "MyTableViewCell.h"


@interface MOPublishedViewController ()<JFImagePickerDelegate,UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate, UINavigationControllerDelegate,UIActionSheetDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView_main;

@property (nonatomic,strong) NSMutableArray *addPhoto;

@property (nonatomic,strong) NSMutableArray *picker;

@property (nonatomic,strong) NSMutableArray *arr_image;

@property (nonatomic,copy) NSString *str_text;

@end

@implementation MOPublishedViewController

- (void)viewDidLoad {
   
    
    
    
    self.title = @"发布动态";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStyleDone target:self action:@selector(send:)];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(exit:)];
    /**
     *  改变textVeiw输入内容位置
     */
    self.automaticallyAdjustsScrollViewInsets = NO;
    //隐藏下划线
    self.tableView_main.separatorStyle = UITableViewCellSeparatorStyleNone;
}


- (void)exit:(UIBarButtonItem *)button{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

/** 判断是否都为空格*/
- (BOOL) isEmpty:(NSString *) str {
    
    if (!str) {
        return true;
    } else {
        //A character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085).
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        
        //Returns a new string made by removing from both ends of the receiver characters contained in a given character set.
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        
        if ([trimedString length] == 0) {
            return true;
        } else {
            return false;
        }
    }
}
- (void)send:(UIBarButtonItem *)button{
    
    
//    UserModel *user = [MOAccountTool account];
//    
//    NSMutableArray *imageDatas = [NSMutableArray array];
//    if (self.addPhoto.count) {
//        
//        for (int count = 0; count < self.addPhoto.count; count ++) {
//            
//            NSData *imageData1 = UIImageJPEGRepresentation(self.addPhoto[count], 1);
//            [imageDatas addObject:imageData1];
//        }
//    }
//    if (self.str_text) {
//        
//    }else {
//        self.str_text = @"";
//    }
//    
//    if ([self isEmpty:self.str_text]  &&  (imageDatas.count == 0)) {
//        [MBProgressHUD showError:@"无效的发布内容"];
//        return;
//    }
//    [MBProgressHUD showMessage:@"发表中....."];
//    NSDictionary *dic = @{@"consumerId":user.id,@"msg":self.str_text};
//    
//    // 向服务器提交图片
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    
//
//    
//    
//    __weak typeof(self) typeof_main = self;
//    
//    // 显示进度
//    [manager POST:[NSString stringWithFormat:@"%@%@",PostUrl,@"saveQuareMsg.jhtml"] parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
//     {
//         NSInteger imgCount = 0;
//         
//         if (imageDatas.count > 0) {
//             for (NSData *imageData in imageDatas) {
//                 
//                 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//                 
//                 formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss:SSS";
//                 
//                 NSString *fileName = [NSString stringWithFormat:@"%@%@.png",[formatter stringFromDate:[NSDate date]],@(imgCount)];
//                 
//                 [formData appendPartWithFileData:imageData name:@"files" fileName:fileName mimeType:@"image/png"];
//                 
//                 imgCount++;
//                 
//             }
//             
//         }else {
//             NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//             
//             formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss:SSS";
//             
//             [formData appendPartWithFileData:[NSData data] name:@"files" fileName:@"" mimeType:@"image/png"];
//         }
//      
//     }
//          success:^(AFHTTPRequestOperation *operation, id responseObject)
//     {
//
//         NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//         if ([result intValue] == 1) {
//             
//               [MBProgressHUD showError:@"发表失败，请重试"];
//       
//             
//         }else {
//             
//             
//             NSArray *array_main = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//             
//             
//             NSLog(@"%@",array_main);
//             
//             NSArray *arrays = [MOStatusOne mj_objectArrayWithKeyValuesArray:array_main];
//             
//            [typeof_main.array insertObject:arrays[0] atIndex:0];
//             
//             
//           
//             if (_reloadTabelView) {
//                 _reloadTabelView();
//             }
//             [typeof_main.navigationController popViewControllerAnimated:YES];
//             
//             [MBProgressHUD hideHUD];
//             [MBProgressHUD showSuccess:@"发表成功"];
//         }
//         
//         
//     }
//          failure:^(AFHTTPRequestOperation *operation, NSError *error)
//     {
//         NSLog(@"错误 %@", error.localizedDescription);
//         [MBProgressHUD hideHUD];
//         [MBProgressHUD showError:@"发表失败"];
//     }];
//    
//    
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id cell_main;
    static NSString *ID_main = @"MyTableViewCell";
    
    
    MyTableViewCell *cellTwo  = [tableView dequeueReusableCellWithIdentifier:ID_main];
    if (!cellTwo) {
        cellTwo = [[[NSBundle mainBundle] loadNibNamed:ID_main owner:nil options:nil] lastObject];
    }
    
    
    
    UITableViewCell *cell = [[UITableViewCell alloc]init];
    
    if (indexPath.section == 0) {
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;//取消点击效果
        
        [self suberViewCell:cell];
    
        cell_main = cell;
        
    }else{
        
        cellTwo.iconName.image = [UIImage imageNamed:@"001"];
        cellTwo.contentLabel.text = @"添加结伴";
        cell_main = cellTwo;
    }
    
  

    
    return cell_main;
}
- (CGFloat )suberViewCell:(UITableViewCell *)cell
{
    //cell高度
    CGFloat cell_H = 0.0;
    
    MOTextView *textVeiw = [[MOTextView alloc] initWithFrame:CGRectMake(15,5, [UIScreen mainScreen].bounds.size.width - 20, 100)];

    textVeiw.didChangeTextView = ^(UITextView *textV){
        self.str_text = textV.text;
    };

    textVeiw.placeholder = @"说点什么吧...";
    textVeiw.font = [UIFont systemFontOfSize:15];
    textVeiw.text = self.str_text;
    [cell.contentView addSubview:textVeiw];
    
 
    
    NSMutableArray *arr_image = [NSMutableArray arrayWithArray:self.addPhoto];
    self.arr_image = arr_image;
    if (arr_image.count != 9) {//如果图片不是9张,把加号添加进去
        UIImage *addImage = [UIImage imageNamed:@"btn_jubao_add"];
        [arr_image addObject:addImage];
    }
    
    //添加九宫格
    for (int i = 0; i < arr_image.count; i++) {
        
        UIImageView *imageV = [[UIImageView alloc]init];
        imageV.image = arr_image[i];//设置图片
        //计算frame
        //自定义一个子的view的大小
        CGFloat subViewW =  100.0;
        CGFloat subViewH = subViewW;
        
        //子view的横向间距 = (父view的宽度 - 3* 子view的宽度) /4
        CGFloat marginX = ([UIScreen mainScreen].bounds.size.width - 3 * subViewW) / 4;
        //子view的纵向间距 (这个是自己定义的)
        CGFloat marginY = 10;
        
        //当前子view的行号 = 当前遍历得到的索引值 / 总列数
        int row = i / 3;
        //当前子view的列号 = 当前遍历得到的索引值 % 总列数
        int column = i % 3;
        
        //子view横坐标公式 = 子view的横向间距 + 列号 * (子view的横向间距 + 子view的高度)
        CGFloat subViewX = marginX + column * (marginX + subViewW);
        
        //子view纵向坐标公式 = 子view的横向间距 + 行号 * (子view的纵向间距 + 子view的高度
        CGFloat subViewY = 20 + row * (marginY + subViewH);
        
        //根据上面计算出的数据 设计出子view的布局
        imageV.frame = CGRectMake(subViewX, subViewY + 100, subViewW, subViewH);
        
        [cell.contentView addSubview:imageV];
        
        if (arr_image.count == 1) {
            //提醒文字Lable
            UILabel *remindLavel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageV.frame)+10, CGRectGetMaxY(imageV.frame)-35, 220, 20)];
            remindLavel.text = @"点击添加图片/点击图片删除图片";
            remindLavel.font = [UIFont systemFontOfSize:12];
            remindLavel.textColor = [UIColor colorWithRed:82 / 250.0 green:82 / 250.0 blue:82 / 250.0 alpha:1];
            [cell.contentView addSubview:remindLavel];
        }
        
        // 单击的 Recognizer
        UITapGestureRecognizer * singleRecognizer;
        singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickImage:)];
        [imageV addGestureRecognizer:singleRecognizer];
        singleRecognizer.numberOfTapsRequired = 1; // 单击
      
        if (i == arr_image.count-1) {//如果是加号,绑定不一样的tag
            imageV.tag = 636300;

        }else{
              imageV.tag = i;
        }
        imageV.userInteractionEnabled = YES;
        
        
        NSLog(@"%ld",singleRecognizer.view.tag);
        
        cell_H = CGRectGetMaxY(imageV.frame)+10;
   
        
        
        
    }
    
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,  cell_H + 20, Swidth , 50)];
    
    [self addControls:view];
    
    [cell.contentView addSubview:view];
    
    return cell_H;
}

- (void)addControls:(UIView *)view{
    
    CGFloat mainX = 15;
    CGFloat mainY = 10;
    
    
    CGFloat buttonX = 115;
    CGFloat buttonWH = 25;
    
    UIImageView *image_main = [[UIImageView alloc] initWithFrame:CGRectMake(mainX, 12, 18, 18)];
    
    image_main.image = [UIImage imageNamed:@"local"];
    
    UILabel *label_main = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(image_main.frame) + 5, 12, 100, 20)];
    label_main.font = [UIFont systemFontOfSize:12.0];
    label_main.textColor = [UIColor colorWithRed:82 / 250.0 green:82 / 250.0 blue:82 / 250.0 alpha:1];
    label_main.text = @"广东市";
    
    UIButton *button_main = [[UIButton alloc] initWithFrame:CGRectMake(Swidth - buttonX, 0, 100, 45)];
    [button_main setTitleColor:[UIColor colorWithRed:82 / 250.0 green:82 / 250.0 blue:82 / 250.0 alpha:1] forState:UIControlStateNormal];
    [button_main setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    [button_main setTitle:@"所有人可见" forState:UIControlStateNormal];
    [button_main setBackgroundImage:[UIImage imageNamed:@"bakgunderImage"] forState:UIControlStateSelected];
    [button_main setBackgroundImage:[UIImage imageNamed:@"bakgunderImage"] forState:UIControlStateHighlighted];
    button_main.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [button_main setImage:[UIImage imageNamed:@"btn_Keyboard_60x60_nol"] forState:UIControlStateNormal];
   // [button_main setImage:[UIImage imageNamed:@""] forState:<#(UIControlState)#>]
    [button_main addTarget:self action:@selector(button_Selected:) forControlEvents:UIControlEventTouchDown];
    
    UIButton *button_Sina = [[UIButton alloc] initWithFrame:CGRectMake(Swidth - buttonX - 35, mainY, buttonWH, buttonWH)];
    [button_Sina setImage:[UIImage imageNamed:@"btn_Keyboard_60x60_nol"] forState:UIControlStateNormal];
    [button_Sina setImage:[UIImage imageNamed:@"btn_Keyboard_60x60_nol"] forState:UIControlStateSelected];
    
    UIButton *button_WeiXin = [[UIButton alloc] initWithFrame:CGRectMake(Swidth - buttonX - buttonWH - 45, mainY, buttonWH, buttonWH)];
    [button_WeiXin setImage:[UIImage imageNamed:@"btn_Keyboard_60x60_nol"] forState:UIControlStateNormal];
    [button_WeiXin setImage:[UIImage imageNamed:@"btn_Keyboard_60x60_nol"] forState:UIControlStateSelected];
    
    UIButton *buton_QQ = [[UIButton alloc] initWithFrame:CGRectMake(Swidth - buttonX - buttonWH * 2 - 55, mainY, buttonWH, buttonWH)];
    [buton_QQ setImage:[UIImage imageNamed:@"btn_Keyboard_60x60_nol"] forState:UIControlStateNormal];
    [buton_QQ setImage:[UIImage imageNamed:@"btn_Keyboard_60x60_nol"] forState:UIControlStateSelected];
    
    [view addSubview:label_main];
    [view addSubview:image_main];
    [view addSubview:button_main];
    [view addSubview:button_Sina];
    [view addSubview:button_WeiXin];
    [view addSubview:buton_QQ];
    
    
    
    
    
}

- (void)button_Selected:(UIButton *)button{
    button.selected = !button.selected;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    CGFloat height = [self suberViewCell:[[UITableViewCell alloc]init]] + 80;
    
    if (indexPath.section == 1) {
        
        height = 50;
    }
    
    
    return height;
}
- (void)clickImage:(UIGestureRecognizer *)singleRecognizer
{
    [self.view endEditing:NO];
    
    NSLog(@"%ld",singleRecognizer.view.tag);
    
    if (singleRecognizer.view.tag == 636300) {
        [self choose];
    }
    else{
        
        // 多选删除
        
        JFImagePickerController *picker = [[JFImagePickerController alloc] initWithPreviewIndex:singleRecognizer.view.tag];
        picker.pickerDelegate = self;
        [self presentViewController:picker animated:YES completion:nil];
        
        
        // 单张 删除
//        [MOAlertView showAlertWithTitle:@"删除图片?" message:nil buttonArrayAsString:@[@"确定",@"取消"] finish:^(NSInteger index) {
//            if (index == 0) {
//                [self.addPhoto removeObjectAtIndex:singleRecognizer.view.tag];
//                [self.tableView_main reloadData];
//            }
//        }];
    }
}



- (void)choose{
    //设置 底部 提示框
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从手机相册选择", nil];
    sheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [sheet showInView:self.view];
    
}

- (void)pickPhotos{
    
    
    JFImagePickerController *picker = [[JFImagePickerController alloc] initWithRootViewController:self];
    picker.pickerDelegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}


#pragma mark - ImagePicker Delegate

- (void)imagePickerDidFinished:(JFImagePickerController *)picker{
    
    __weak typeof(self) weakSelf = self;
    
    [self.addPhoto removeAllObjects];
    [self.picker removeAllObjects];
    [self.arr_image removeAllObjects];
    
    [self.picker addObjectsFromArray:picker.assets];
    
    for (int i = 0; i < self.picker.count; i++) {
        
        
        ALAsset *asset = weakSelf.picker[i];

        [[JFImageManager sharedManager] thumbWithAsset:asset resultHandler:^(UIImage *result) {

            
            [weakSelf.addPhoto addObject:result];
            
        }];
    
    }
    
    [self.tableView_main reloadData];
    [self imagePickerDidCancel:picker];
    
    
}

- (void)imagePickerDidCancel:(JFImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}










/*
 * 点击了那个按钮的监听事件  (代理方法)
 */
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    
    
    if (buttonIndex == 0) {
        //打开相机
        //资源类型为照相机
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        //判断是否有相机
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            //设置拍照后的图片可被编辑
            picker.allowsEditing = YES;
            //资源类型为照相机
            picker.sourceType = sourceType;
            [self presentViewController:picker animated:YES completion:^(){}];
        }else {
           // [MBProgressHUD showError:@"该设备无摄像头"];
        }
        
        
    }else if(buttonIndex == 1){
      
    
        [self pickPhotos];
        
    }
    
}
#pragma mark - 选择图片完成的时候调用
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
//    
//    if (picker.sourceType == UIImagePickerControllerSourceTypeSavedPhotosAlbum) {
//        UIImage *icon=[info objectForKey:@"UIImagePickerControllerOriginalImage"];
//        //关闭
//        [self dismissViewControllerAnimated:YES completion:nil];
//        //缩小尺寸
//        UIImage *iconimg=[ self imgWithImage:icon];
//        //压缩
//        NSData *data=UIImageJPEGRepresentation(iconimg, 1);
//        UIImage *img=[UIImage imageWithData:data];
//        //        self.iconName.image = img;
//        [self.addPhoto addObject:img];
//        
//        
//    }else if (picker.sourceType == UIImagePickerControllerSourceTypeCamera){
//        UIImage *icon=[info objectForKey:@"UIImagePickerControllerEditedImage"];
//        
//        //关闭
//        [self dismissViewControllerAnimated:YES completion:nil];
//        //缩小尺寸
//        UIImage *iconimg=[ self imgWithImage:icon];
//        //压缩
//        NSData *data=UIImageJPEGRepresentation(iconimg, 1);
//        UIImage *img=[UIImage imageWithData:data];
//        [self.addPhoto addObject:img];
//        
//    }
//    
//    [self.tableView_main reloadData];
//    
//    [self dismissViewControllerAnimated:YES completion:nil];
}
//MARK:缩小照片的尺寸
-(UIImage *)imgWithImage:(UIImage *)img{
    //获取上下文
    //固定图片宽高
    //    CGFloat w=(Swidth-40)/4;
    //    CGFloat h=50;
    CGFloat w=500;
    CGFloat h=500;
    
    //开启图片上下文
    UIGraphicsBeginImageContext(CGSizeMake(w, h));
    //绘制
    [img drawInRect:CGRectMake(0, 0, w, h)];
    //从上下文获取图片
    UIImage *newImg=UIGraphicsGetImageFromCurrentImageContext();
    //关闭上下文
    UIGraphicsEndImageContext();
    return newImg;
}



-(NSMutableArray *)addPhoto
{
    if (!_addPhoto) {
        _addPhoto = [NSMutableArray array];
    }
    return _addPhoto;
}

- (NSMutableArray *)picker{
    if (!_picker) {
        _picker = [NSMutableArray array];
    }
    return _picker;
}

- (NSMutableArray *)arr_image{
    if (!_arr_image) {
        _arr_image = [NSMutableArray array];
    }
    return _arr_image;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.1;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10.0;
}
@end
